package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.StockIncomeBill;
import cn.wolfcode.wms.domain.StockIncomeBillItem;
import cn.wolfcode.wms.mapper.StockIncomeBillItemMapper;
import cn.wolfcode.wms.mapper.StockIncomeBillMapper;
import cn.wolfcode.wms.page.PageResult;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IProductStockService;
import cn.wolfcode.wms.service.IStockIncomeBillService;
import cn.wolfcode.wms.util.UserContext;
import cn.wolfcode.wms.web.exception.LogicalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

@Service
public class StockIncomeBillServiceImpl implements IStockIncomeBillService {
    @Autowired
    private StockIncomeBillMapper billMapper;
    @Autowired
    private StockIncomeBillItemMapper itemMapper;
    @Autowired
    private IProductStockService stockService;

    public void save(StockIncomeBill orderBill) {
        billMapper.insert(orderBill);
    }

    public void delete(long id) {
        StockIncomeBill orderBill = billMapper.selectByPrimaryKey(id);
        if (orderBill.getStatus() == StockIncomeBill.STATUS_NORMAL) {
            itemMapper.deleteByBillId(id);
            billMapper.deleteByPrimaryKey(id);
        }else{
            throw new LogicalException("该订单已经审核无法删除!");
        }
    }

    public void update(StockIncomeBill orderBill) {
        billMapper.updateByPrimaryKey(orderBill);
    }

    public StockIncomeBill get(long id) {
        return billMapper.selectByPrimaryKey(id);
    }

    public List<StockIncomeBill> list() {
        return billMapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int rows = billMapper.queryForCount(qo);
        if (rows == 0) {
            return PageResult.empty(qo.getPageSize());
        }
        List<?> result = billMapper.queryForList(qo);
        return new PageResult(result, rows, qo.getCurrentPage(), qo.getPageSize());
    }

    public void saveOrUpdate(StockIncomeBill orderBill) {
        if (orderBill.getId() == null) {
            saveBill(orderBill);
        } else {
            updateBill(orderBill);
        }
    }

    public void audit(Long id) {
        //1.判断入库单的状态
        StockIncomeBill bill = billMapper.selectByPrimaryKey(id);
        if(bill.getStatus() == StockIncomeBill.STATUS_AUDITED){
            throw new LogicalException("入库单已审核!");
        }
        //2.设置入库单的审核人相关信息
        bill.setAuditTime(new Date());
        bill.setAuditor(UserContext.getCurrentUser());
        //3.设置入库单的状态为已审核
        bill.setStatus(StockIncomeBill.STATUS_AUDITED);
        //4.更新入库单中的明细
        //4.1判断库存当中是否已经有明细当中的商品了
        billMapper.audit(bill);
        //======================库存操作========================
        stockService.stockIncome(bill);
    }
    private void updateBill(StockIncomeBill bill) {
        //1.判断该订单的状态
        Integer status = billMapper.selectByPrimaryKey(bill.getId()).getStatus();
        if(status == StockIncomeBill.STATUS_AUDITED){
            throw new LogicalException("该订单已审核无法更改!");
        }else{
            //删除该订单中所有的明细
            itemMapper.deleteByBillId(bill.getId());
            BigDecimal totalNumber = BigDecimal.ZERO;
            BigDecimal totalAmount = BigDecimal.ZERO;
            //计算明细的小计并设置进去
            for (StockIncomeBillItem item : bill.getItems()) {
                BigDecimal amount = item.getCostPrice().multiply(item.getNumber()).setScale(2, RoundingMode.HALF_UP);
                item.setAmount(amount);
                totalAmount = totalAmount.add(amount);
                totalNumber = totalNumber.add(item.getNumber());
                item.setBillId(bill.getId());
                itemMapper.insert(item);
            }
            bill.setTotalNumber(totalNumber);
            bill.setTotalAmount(totalAmount);
            billMapper.updateByPrimaryKey(bill);
        }
    }

    public void saveBill(StockIncomeBill bill) {
        //1.设置录入人相关信息
        bill.setInputUser(UserContext.getCurrentUser());
        bill.setInputTime(new Date());
        //2.将订单状态设置为未审核
        bill.setStatus(StockIncomeBill.STATUS_NORMAL);
        //3.定义总数量和总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal totalNumber = BigDecimal.ZERO;
        //4.遍历订单明细,计算小计
        for (StockIncomeBillItem item : bill.getItems()) {
            //设置订单明细的小计
            BigDecimal amount = item.getNumber().multiply(item.getCostPrice()).setScale(2, RoundingMode.HALF_UP);
            item.setAmount(amount);
            //计算订单的总金额和总数量
            totalNumber = totalNumber.add(item.getNumber());
            totalAmount = totalAmount.add(amount);
        }
        //设置订单的金额和数量
        bill.setTotalAmount(totalAmount);
        bill.setTotalNumber(totalNumber);
        //保存订单
        billMapper.insert(bill);
        //设置明细的订单ID并保存明细
        for (StockIncomeBillItem item : bill.getItems()) {
            item.setBillId(bill.getId());
            itemMapper.insert(item);
        }
    }
}
